package com.zhdl.hardware.motor.leisai.service.impl;

import com.zhdl.common.ytools.callback.CommonCallback;
import com.zhdl.hardware.motor.leisai.repository.LeisaiPortCmdHandleDao;
import com.zhdl.hardware.motor.leisai.service.LSCmdSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Slf4j
@Service
public class LSCmdSendServiceImpl implements LSCmdSendService {

    @Resource
    public ThreadPoolTaskScheduler taskScheduler1;
    @Resource
    public LeisaiPortCmdHandleDao handleDao;
    Map<String, ScheduledFuture<?>> mapSF = new HashMap<>();

    /**
     * 读取电机当前位置
     *
     * @param port           串口
     * @param slaveStationId 从站Id
     */
    @Override
    public void leisaiReadCurrentLocation(String port, String slaveStationId, CommonCallback<String> callback) {
        ScheduledFuture<?> scheduledFuture = taskScheduler1.scheduleWithFixedDelay(() -> {
            handleDao.leisaiReadCurrentLocation(port, slaveStationId, s -> {
                callback.statusCallback(s);
                log.info("");
            });
        }, 200);

        mapSF.put("no1", scheduledFuture);
    }

    @Override
    public void cancelScheduledFuture() {
        ScheduledFuture<?> scheduledFuture = mapSF.get("no1");
        scheduledFuture.cancel(true);
    }

    /**
     * 设置电机移动距离
     *
     * @param port           串口
     * @param slaveStationId 从站Id
     * @param distance       距离
     */
    @Override
    public void leisaiSetMoveDist(String port, String slaveStationId, int distance) {
        handleDao.leisaiSetMoveDist(port, slaveStationId, distance);
        log.info("雷赛电机-端口为_" + port + ",从站为_" + slaveStationId + ",距离为_" + distance);
    }

    /**
     * 雷赛电机-电机移动速度
     *
     * @param slaveStationId 从站Id
     * @param speed          写入值
     */
    @Override
    public void leisaiSetMoveSpeed(String port, String slaveStationId, int speed) {
        handleDao.leisaiSetMoveSpeed(port, slaveStationId, speed);
        log.info("雷赛电机-端口为_" + port + ",从站为_" + slaveStationId + ",速度为_" + speed);
    }
}
